/**
 * The Footbar global namespace
 * @class Footbar.TeamSpeakService
 * @static
 */

if (typeof Footbar == "undefined") {
    Footbar = {};
}

Footbar.TeamSpeakService={
   XML_USERS:"chrome://footbar/content/xml/teamspeak-users.xml",
   serverSocket:null,
   isServerRunning:false,

/**
 * InitalizeService
 */
    init: function() {
        this.populateGroups();
    },

    /**
     * Start the TeamSpeak Server
     */
    startServer:function(){
      var transportService =Components.classes["@mozilla.org/network/socket-transport-service;1"].getService(Components.interfaces.nsISocketTransportService);
      var transport = transportService.createTransport(null,0,"127.0.0.1",80,null);

        var contentRead="";

      //Send dataout
      var outputData="GET / HTTP/1.0\n\n";  
      var outstream=transport.openOutputStream(0,0,0);
          outstream.write(outputData,outputData.length);

        //Read datain
       var stream = transport.openInputStream(0,0,0);
       var scriptablestream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);        
          scriptablestream.init(stream);

        var dataListener = {
            onStartRequest: function(request, context){},
            onStopRequest: function(request, context, status){
                scriptablestream.close();
                outstream.close();
                dump("\n contentRead=" +contentRead);
            },
            onDataAvailable: function(request, context, inputStream, offset, count){
                contentRead += scriptablestream.read(count);
            }
        };

        //Pump data as it is loaded from the socket
         var pump = Components.classes["@mozilla.org/network/input-stream-pump;1"].createInstance(Components.interfaces.nsIInputStreamPump);
            pump.init(stream, -1, -1, 0, 0, false);
            pump.asyncRead(dataListener,null);

    },
/**
 * Stop running server
 */
    stopServer:function(){
        alert("Stopping Server")
        this.isServerRunning=false;
        if(this.serverSocket){
             try{
                this.serverSocket.close();
             }catch(e){
                dump("\n "+e);
             }
         }
    },
/**
 * Toggle server state if running  then stop else start
 */
    toggleServerState:function(){
        var btn=document.getElementById("trucoder-teamspeak-btn-serverstate");
      //  alert("this.isServerRunning="+this.isServerRunning);
        if(this.isServerRunning){
            dump("\n  Stopping Server");           
            this.stopServer();
            btn.image="";
            btn.label=" Start Server";
        }else{
            dump("\n  Starting Server");
            btn.label=" Stop Server";
            btn.image="/skin/indicator.gif";
            this.startServer();
        }
    },
/**
 * Register new Group
 */
    registerGroup:function(group){
        var uid=Footbar.Util.uid();
        var xmlDoc=this.loadSourceXML();
        var root=xmlDoc.getElementsByTagName('root')[0];
        var newNode=document.createElement('group');
        newNode.setAttribute("name",group);
        newNode.setAttribute("uid", uid);
        root.appendChild(newNode);   

        var filePath=Footbar.Util.findPluginPath(true)+"chrome\\content\\xml\\teamspeak-users.xml";
        var output='<?xml version="1.0" encoding="iso-8859-1"?>\n'+Footbar.Util.serializeNode(xmlDoc, 0);
        Footbar.Util.writeFileData(filePath, output);

        this.populateGroups();

    },
    /**
     * Register new user in a group
    */
    registerGroupUser:function(){
        //Find selected node and then check for parent
       var selectedRow=Footbar.TreeUtil.getSelectedRow('trucoder-set-tree-srv-teamspeak');
        if(!selectedRow){
            alert("Select parent node first.")
           return;
        }

        if(!selectedRow.hasAttribute("container")){
           selectedRow=Footbar.TreeUtil.findParentNode( selectedRow );
        }

        //Request Info in dialog
        var params = {inn:{}, out:null};
       window.openDialog("chrome://footbar/content/teamspeak-adduser.xul","", "modal", params);
       
        var rowData=selectedRow.getElementsByTagName('treecell')[0];
        var uid=rowData.getAttribute('key');

        try{
            var xmlDoc=this.loadSourceXML();
                    var root=xmlDoc.getElementsByTagName('root')[0];
                    var iteratorRow = xmlDoc.evaluate( '/root/group[@uid="'+uid+'"]', xmlDoc, null, XPathResult.ANY_TYPE, null );
                    var thisNode=iteratorRow.iterateNext();
                    var newNode=document.createElement('user');
                    newNode.setAttribute("type",1);
                    newNode.setAttribute("username", params.out.username);
                    newNode.setAttribute("uid", Footbar.Util.uid());

                    var tcpEndPoint=document.createElement('tcpEndPoint');
                    var host=document.createElement('host');
                    var port=document.createElement('port');

                    host.textContent=params.out.host;
                    port.textContent=params.out.port;
                    tcpEndPoint.appendChild(host);
                    tcpEndPoint.appendChild(port);

                    newNode.appendChild(tcpEndPoint);
                    thisNode.appendChild(newNode);

                    var filePath=Footbar.Util.findPluginPath(true)+"chrome\\content\\xml\\teamspeak-users.xml";
                    var output='<?xml version="1.0" encoding="iso-8859-1"?>\n'+Footbar.Util.serializeNode(xmlDoc, 0);
                    Footbar.Util.writeFileData(filePath, output);
                this.populateGroups();
                Footbar.Util.notifyMessage("New TeamSpeak user '"+params.out.username+"' added");
        }catch(e){
            alert(e);
        }


        //Request Info in dialog
       //var params = {inn:{}, out:null};
       //window.openDialog("chrome://footbar/content/teamspeak-adduser.xul","", "modal", params);

        /*
        var uid=Footbar.Util.uid();
        var xmlDoc=this.loadSourceXML();
        var newNode=document.createElement('user');
        newNode.setAttribute("type",group);
        newNode.setAttribute("username", uid);
        newNode.setAttribute("uid", uid);
        selectedRow.appendChild(newNode);

        var filePath=Footbar.Util.findPluginPath(true)+"chrome\\content\\xml\\teamspeak-users.xml";
        var output='<?xml version="1.0" encoding="iso-8859-1"?>\n'+Footbar.Util.serializeNode(xmlDoc, 0);
        Footbar.Util.writeFileData(filePath, output);

        this.populateGroups();
        */
    },

    populateGroups:function(){
        //Prepare the tree : delete all the node from the treechildren
        var tree=document.getElementById( 'trucoder-set-tree-srv-teamspeak' );
        var rootElements=tree.getElementsByTagName("treechildren")[0];
        try {
            while (rootElements.firstChild){
                rootElements.removeChild(rootElements.firstChild);
            };
        } catch(e) {
            alert(e)
        }


        var xmldata = this.loadSourceXML();
        var root = xmldata.getElementsByTagName("root")[0];
        var items = root.getElementsByTagName("group");


        var tree=document.getElementById( 'trucoder-set-tree-srv-teamspeak' );
        var	treechildren = tree.getElementsByTagName("treechildren")[0];

        for (var i=0;i<items.length;i++){
            var itemrow=items[i];

            var label_title= document.createElement("treecell");
            label_title.setAttribute("label",  itemrow.getAttribute("name"))
            label_title.setAttribute("key",  itemrow.getAttribute("uid"))
            var	treerow = document.createElement("treerow");
            treerow.setAttribute("id",  "setname-treerow-"+i);

            var	treeitem = document.createElement("treeitem");
            treeitem.setAttribute("container", "true");
            treeitem.setAttribute("open", "true");
            var  sub_treechildren = document.createElement("treechildren");


            var uriList=itemrow.getElementsByTagName("user");
            for(var k=0;k<uriList.length;k++){
                sub_treechildren.appendChild( Footbar.TreeUtil.cellNode({
                    label:uriList[k].getAttribute("username"),
                    type:uriList[k].getAttribute("type"),
                    uid:uriList[k].getAttribute("uid")
                }) );

            }
    
            treerow.appendChild(label_title);
            treeitem.appendChild(treerow);
            treeitem.appendChild(sub_treechildren);
            treechildren.appendChild(treeitem);

        }
       
    },

/**
 * Load Set XML File
 */
    loadSourceXML:function(){
        var httpRequest;
        httpRequest = new XMLHttpRequest();
        httpRequest.overrideMimeType('text/xml');
        httpRequest.open('GET', this.XML_USERS, false);
        httpRequest.send(null);
        return httpRequest.responseXML;
    }

}